20. Valid Parentheses (有效的括号)

问题描述

英文

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

中文

给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

Solution

Python

Method 1:

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s) % 2 != 0:
            return False
        
        d = {'(':')', '[':']', '{':'}'}
        stack = []
        for i in s:
            if not stack and i in d.values():
                return False
            elif i in d.keys():
                stack.append(i)
            elif stack and i == d.get(stack[-1]):
                stack.pop()
        if not stack:
            return True
        else:
            return False
Submissions

执行用时 :24 ms, 在所有 python3 提交中击败了99.90%的用户 内存消耗 :12.6 MB, 在所有 python3 提交中击败了99.66%的用户

JavaScript

Go